#ifndef xpack_lang_cxx_index_of_last
#define xpack_lang_cxx_index_of_last
#pragma push_macro("xuser")
#undef  xuser
#define xuser mixc::lang_cxx::inc
#include"define/base_type.hpp"
#include"lang/cxx.hpp"
#pragma pop_macro("xuser")

namespace mixc::lang_cxx{
    inline cxx_index_pair index_of_last_core(auto main, auto pattern, auto const & compare) {
        auto result         = cxx_index_pair{};
        result->i_main      = not_exist;
        result->i_pattern   = not_exist;

        for(uxx i = main->length; i-- > 0;){
            for(uxx j = pattern->length; j-- > 0;){
                // 约定:
                // left 为待匹配字符串的字符，right 为匹配参数字符
                if (compare(main[i], pattern[j]) == 0){
                    result->i_main = i;
                    result->i_pattern = j;
                    return result;
                }
            }
        }
        return result;
    }


    template<class item_t>
    template<class item_seq_t, class>
    inline cxx_index_pair cxx<item_t>::index_of_last(item_seq_t const & value, invoke_compare_t compare) const {
        return index_of_last_core(xthe, inc::unified_seq<item_seq_t>(value), compare);
    }

    template<class item_t>
    inline uxx cxx<item_t>::index_of_last(item_cref_t value, invoke_compare_t compare) const {
        for(uxx i = xthe->length; i-- > 0;){
            // 约定:
            // left 为待匹配字符串的字符，right 为匹配参数字符
            if (compare(xthe[i], value) == 0){
                return i;
            }
        }
        return not_exist;
    }

    template<class item_t>
    inline uxx cxx<item_t>::index_of_last(the_cref_t value, invoke_compare_t compare) const {
        // miss 为未匹配项的索引
        // 每次都去匹配上一次未匹配的字符 str[miss]
        // 每当在 index 处匹配，就将原串缩短 index - miss + 1
        //      剩余可匹配的串
        //            |
        //         |--+--|
        // origin "123451235"
        // value         "34"
        the_t   origin = xthe;
        the_t   temp   = xthe;
        uxx     miss   = 0;
        uxx     index;

        if (origin->length < value->length or value->length == zero) {
            return not_exist;
        }
        for (origin = origin.shorten(value->length - 1);;){
            if (index = origin.index_of_last(value[miss], compare); 
                index == not_exist){
                break;
            }

            origin->length  = index - miss;
            temp            = origin.backward(origin->length);
            origin          = origin.elongate(1);
            
            for(index = 0; ; index++){
                if (index == value->length) {
                    return origin->length - 1;
                }

                // 约定:
                // left 为待匹配字符串的字符，right 为匹配参数字符
                if (compare(temp[index], value[index]) != 0) {
                    miss = index;
                    break;
                }
            }
        }
        return not_exist;
    }
}

#endif

